package com.pig4cloud.pig.ads.aop;

import com.pig4cloud.pig.ads.utils.RedisLock;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.api.util.NoRepeatSubmit;
import com.pig4cloud.pig.api.util.RequestUtils;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Slf4j
@Aspect
@Component
public class RepeatSubmitAspect {

	@Autowired
	private RedisLock redisLock;

	@Pointcut("@annotation(noRepeatSubmit)")
	public void pointCut(NoRepeatSubmit noRepeatSubmit) {
	}

	@Around("pointCut(noRepeatSubmit)")
	public Object around(ProceedingJoinPoint pjp, NoRepeatSubmit noRepeatSubmit) throws Throwable {
		long lockSeconds = noRepeatSubmit.lockTime();

		HttpServletRequest request = RequestUtils.getRequest();
		Assert.notNull(request, "request can not null");

		// 此处可以用token或者JSessionId
		String token = request.getHeader("Authorization");
		String path = request.getServletPath();
		String key = getKey(token, path);
		String clientId = getClientId();

		String getToken = redisLock.tryLock(key, lockSeconds);

		if (StringUtils.isNotBlank(getToken)) {
			log.info("tryLock success, key = [{}], clientId = [{}]", key, clientId);
			// 获取锁成功, 执行进程
			Object result;
			try {
				result = pjp.proceed();

			} finally {
				// 解锁
				redisLock.unlock(key, getToken);
				log.info("releaseLock success, key = [{}], clientId = [{}]", key, clientId);

			}

			return result;

		} else {
			// 获取锁失败，认为是重复提交的请求
			log.info("tryLock fail, key = [{}]", key);
			return R.failed("重复请求，请稍后再试");
		}

	}

	private String getKey(String token, String path) {
		return token + path;
	}

	private String getClientId() {
		return UUID.randomUUID().toString();
	}

}
